var hdsavings = (function () {
    var returnid, sID = 0;
    this.ShowPage = function (pageid) {
        returnid = pageid;
        $.mobile.changePage("#page8");
    };
    function Refresh (results){
        var i, num, str = "";
        num = results.rows.length;
        if (num !== 0) {
            for(i=0; i < num; i += 1){
                str += "<li><a style='display: inline-block; padding: 14px; font-size: 14px;' savingID='" +
                    results.rows.item(i).SavingID + "' >" + results.rows.item(i).Name + ": </a>" +
                    "<span style='display: inline-block; font-size: 10px;'>" + addCommas(results.rows.item(i).Sum) +
                    " RSD</span></li>";
            }

        }
        $("#lvSavingsList").html(str).listview('refresh');
    }
    this.updateSavings = function (){
        data.getSavingsList(Refresh);
    };

    this.init = function (){
        $("#btnSavingsListCancel").click(function () {
            $.mobile.changePage("#page" + returnid);
        });
        $("#btnAddSavings").click(function(){
            $("#txtSavingName").val("");
            sID = 0;
            $("#btnDeleteSaving").css("display","none");
        });
        $("#btnSavingSubmit").click(function () {
            var newData;

            newData = {
                SavingID: sID,
                Name:$("#txtSavingName").val(),
                Sum: 0
            };
            if(sID === 0){
                data.saveSavings(
                    function () {
                        data.getSavingsList( Refresh );
                        $("#txtSavingName").val("");
                        $.mobile.changePage("#page8");
                    }
                    , newData
                );
            }else{
                data.editSaving(
                    function () {
                        data.getSavingsList( Refresh );
                        $("#txtSavingName").val("");
                        $.mobile.changePage("#page8");
                    }, newData
                );
            }
        });
        $("#lvSavingsList").delegate("li", "click", function () {
            sID = parseInt($("a",this).attr("savingID"));
            $("#txtSavingName").val($("a",this).html().split(':')[0]);
            $("#btnDeleteSaving").css("display","block");
            $.mobile.changePage("#page9");
        });
        $("#btnDeleteSaving").click( function (){
            data.deleteSaving(sID,Refresh);
            $("#txtSavingName").val("");
            $.mobile.changePage("#page8");
        });
    };

    this.init();
    return this;
}(hdsavings || {}))